package com.otojob.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.otojob.dto.PageDto;
import com.otojob.entity.Company;
import com.otojob.entity.Job;
import com.otojob.entity.User;
import com.otojob.entity.UserJob;
import com.otojob.entity.data.JobData;
import com.otojob.entity.vo.JobDetails;
import com.otojob.entity.vo.JobFrontVo;
import com.otojob.entity.vo.ReleaseJob;
import com.otojob.listener.JobExcelListener;
import com.otojob.mapper.CompanyMapper;
import com.otojob.mapper.JobMapper;
import com.otojob.mapper.UserJobMapper;
import com.otojob.mapper.UserMapper;
import com.otojob.service.JobService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.otojob.utils.JwtUtils;
import com.otojob.utils.OtoException;
import com.otojob.utils.Results;
import lombok.extern.slf4j.Slf4j;
import org.mapstruct.BeforeMapping;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.rmi.runtime.Log;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author TingFeng
 * @since 2022-03-18
 */
@Slf4j
@Service
public class JobServiceImpl extends ServiceImpl<JobMapper, Job> implements JobService {

    @Resource
    private JobMapper jobMapper;
    @Resource
    private CompanyMapper companyMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UserJobMapper userJobMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 通过JObId查找工作详情
     * @param id
     * @return
     */
    @Override
    public Results findJobDetails(Integer id) {
        Map<String, Object> map = new HashMap<>();
//        JobDetails jobDetailsByJobId = baseMapper.findJobDetailsByJobId(id);
        JobDetails jobDetailsByJobId = baseMapper.findJobDetailsByJobId(id);
        map.put("jobDetails",jobDetailsByJobId);


//        try {
//            JobDetails jobDetailsByJobId = baseMapper.findJobDetailsByJobId(id);
//            map.put("jobDetails",jobDetailsByJobId);
//        }catch (Exception e){
//            throw new OtoException(2000,"查询失败");
//        }
        return Results.ok().data(map);

    }




    /**
     * 发布职业
     * @param releaseJob
     * @return
     */
    @Override
    public Results releaseJob(ReleaseJob releaseJob,int userId) {

        Company companyById = companyMapper.findCompanyById(userId);
        int i = userMapper.findUser(userId);

        if(companyById==null){
            Results.error().message("未进行企业认证，请认证");
        }

        if(i!=1){
            return Results.error().message("该用户未注册");
        }
        Job job = new Job();
        BeanUtils.copyProperties(releaseJob,job);
        job.setUserId(userId);
        boolean wqe= jobMapper.addreleaseJob(job);
        return Results.ok();
    }
    /**
     * 删除已发布职位
     * @param id
     * @return
     */
    @Override
    public Results deleteJobById(Integer id,int userId) {
        Job jobByJobId = jobMapper.findJobByJobId(id);
        if(userId!=jobByJobId.getUserId()){
            return Results.error().message("你没有该权限");
        }

        int i =jobMapper.deleteJobById(id);
        if(i==0){
            return Results.error().message("未找到此职位");
        }
        return Results.ok().message("下线成功");
    }
    /**
     * 查询已发布职位

     * @return
     */

    @Override
    public Results findReleasedJob(int userId) {

        List<JobFrontVo> jobByUserId = jobMapper.findJobByUserId(userId);
        for (JobFrontVo jobFrontVo : jobByUserId) {
            String[] split = jobFrontVo.getPlace().split("-");
            jobFrontVo.setPlace(split[0]);
        }
        System.out.println(userId);
        Map<String,Object> map = new HashMap<>();
        map.put("已发布职业",jobByUserId);
        return Results.ok().data(map);
    }
    /**
     * 查找所有招聘信息分页
     * @param pageDto
     * @return
     */
    @Override
    public Results findAllJobList(PageDto pageDto) {

        int numPage=pageDto.getPageNum();
        int numSize=pageDto.getPageSize();

        List<JobFrontVo> listJob = jobMapper.findAllJobList((numPage-1)*numSize,numSize);
        for (JobFrontVo jobFrontVo : listJob) {
            String[] split = jobFrontVo.getPlace().split("-");
            jobFrontVo.setPlace(split[0]);
        }

//        int totals = jobMapper.findAllJob();
        int totals = listJob.size();
        int pages = (int) Math.ceil(totals/numSize);
        Collections.shuffle(listJob);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("numPage",numPage);
        map.put("numSize",numSize);
        map.put("totals",totals);
        map.put("pages",pages);
        map.put("listJob",listJob);
        return Results.ok().data(map);
    }

    /**
     * 模糊查询带分页
     * @param pageDto
     * @return
     */
//    @Cacheable(value = "job",key="'searchByConditions'")
    @Override
    public Results searchByConditions(PageDto pageDto,String condition) {

        int numPage=pageDto.getPageNum();
        int numSize=pageDto.getPageSize();

        List<JobFrontVo> jobList = jobMapper.searchByConditions((numPage-1)*numSize,numSize,condition);
        for (JobFrontVo jobFrontVo : jobList) {
            String[] split = jobFrontVo.getPlace().split("-");
            jobFrontVo.setPlace(split[0]);
        }
        int totals = jobList.size();
        int pages = (int) Math.ceil(totals/numSize);

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("numPage",numPage);
        map.put("numSize",numSize);
        map.put("totals",totals);
        map.put("pages",pages);
        map.put("listJob",jobList);
        return Results.ok().data(map);
    }

    /**
     * 投递简历
     * @param jobId
     * @return
     */
    @Override
    public Results sendResume(Integer jobId) {
        int userId = JwtUtils.getMemberIdByJwtToken(request);
        User allById = userMapper.findAllById(userId);
        if(allById==null){
            throw new OtoException(500000,"未登入");
        }
        /**
         * 添加重复投递拦截
         */


        int myResumeTF = userMapper.findMyResumeTF(userId);
        if(myResumeTF<1){
            return Results.error().message("请添加简历");
        }
        int i = userJobMapper.findSendResume(userId,jobId);
        if(i>0){
            return Results.error().message("请勿重复投递");
        }

        UserJob userJob = new UserJob();
        userJob.setJobId(jobId)
                .setUserId(userId);
        userJobMapper.sendResume(userJob);
        log.info("投递成功");
        return Results.ok();
    }
}
